import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';

class SonMaterialAcionDialog extends StatefulWidget {
  final String baseApi;
  final int orderId;
  final String type;
  final Map item;
  final onSubmit;
  final Map numForm;
  final String title;
  final List ids;

  SonMaterialAcionDialog(
      {Key key,
      this.baseApi = 'EnterMaterialSon/',
      this.orderId,
      this.type,
      this.item,
      this.onSubmit,
      this.numForm,
      this.title,
      this.ids})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => SonMaterialAcionDialogState();
}

class SonMaterialAcionDialogState extends State<SonMaterialAcionDialog> {
  String baseApi = 'EnterMaterialSon/';

  TextEditingController _remarkController = new TextEditingController();
  TextEditingController _sonNumController = new TextEditingController();

  var eventBus = new EventBus();

  @override
  void initState() {
    super.initState();
    setState(() {
      baseApi = widget.baseApi;
    });
    print(widget.ids);
    // initEditData();
    // // 监听物资分类选择
    // eventBus.on("enter_mct", (parmas){
    //   var p = parmas['select'];
    //   setState(() {
    //     materialTypeId = p['id'];
    //     materialTypeName = p['name'];
    //   });
    // });
  }

  // 添加物资
  _editNum() {
    var num = _sonNumController.text.trim();
    var list = widget.ids;
    var numForm = widget.numForm;
    var data = [];
    // 总数和入库数量
    var totalEnter = 0;
    var realEnter = 0;

    if (num.isEmpty) {
      Utils.showText(text: '请输入子物资数量', align: Alignment(0, 0));
      return;
    }

    if (int.tryParse(num) == null) {
      Utils.showText(text: '请输入数字', align: Alignment(0, 0));
      return;
    }

    list.forEach((item) {
      totalEnter += int.parse(num);
      // realEnter += int.parse(item['num']);
      realEnter += item['num'];
      data.add({'num': num, 'id': item['id']});
    });

    if (totalEnter > numForm['num'] - numForm['y_num'] + realEnter) {
      Utils.showText(text: '更新数量大于物资总数量', align: Alignment(0, 0));
      return;
    }

    // if(int.parse(son_num) > widget.numForm['d_num']) {
    //    Utils.showText(text: '子物资数量大于子物资数量', align: Alignment(0,0));
    //   return;
    // }

    DioUtils.request("${baseApi}batchUpdMaterialSonNum",
        context: context,
        method: "POST",
        params: {'enter_material_id': widget.item['id'], 'data': data},
        onSuccess: (res) {
      Utils.showText(text: res['msg']);
      if (res['code'] == 1) {
        widget.onSubmit({'type': 'num', 'list': data});
        Navigator.pop(context);
      }
    }, onError: (error) {});
  }

  // 编辑物资
  _editRemark() {
    // int id = widget.item['id'];
    var list = widget.ids;
    var remark = _remarkController.text.trim();
    var ids = [];
    list.forEach((item) {
      ids.add(item['id']);
    });

    if (remark.isEmpty) {
      Utils.showText(text: '请输入备注', align: Alignment(0, 0));
      return;
    }

    DioUtils.request("${baseApi}batchUpdMaterialSonRemark",
        context: context,
        method: "POST",
        params: {
          'ids': ids,
          'remark': remark,
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);
      if (res['code'] == 1) {
        widget.onSubmit({'type': 'remark'});
        Navigator.pop(context);
      }
    }, onError: (error) {});
  }

  Widget _buildDialogHead(title) {
    return Container(
      height: 80.w,
      decoration: BoxDecoration(
          color: Utils.hexToColor('#F7F7F7'),
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.w), topRight: Radius.circular(12.w))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 31.w),
            child: Text(title,
                style: TextStyle(
                    color: Utils.hexToColor('#333333'),
                    fontSize: 16,
                    fontWeight: FontWeight.bold)),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(30.w, 24.w, 30.w, 24.w),
              alignment: Alignment.topRight,
              child: Image.asset(
                'assets/dialog_close.png',
                width: 36.w,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildInput(title, controller, [isNumber = false, maxLines = 1]) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 160.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 460.w,
            height: maxLines > 1 ? 200.h : 70.h,
            child: TextField(
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(isNumber ? '[0-9]' : '[^]')),
              ],
              maxLines: maxLines,
              controller: controller,
              style: TextStyle(fontSize: 14, color: Colors.black), //输入文本的样式
              decoration: InputDecoration(
                hintText: '暂无',
                hintStyle: TextStyle(color: Color(0xFFC8C8D9), fontSize: 14),
                contentPadding: EdgeInsets.fromLTRB(21.w, 10, 21.w, 10),
                fillColor: Colors.white,
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInputWrap(type) {
    if (type == 'num') {
      return _buildInput('数量', _sonNumController, true);
    } else {
      return _buildInput('备注', _remarkController, false, 5);
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Container(
        width: 700.w,
        height: 500.w,
        decoration:
            BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100))),
        child: Column(
          children: <Widget>[
            _buildDialogHead('${widget.title ?? '标题'}'),
            Expanded(
              flex: 1,
              child: Container(
                  padding: EdgeInsets.all(40.w),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      // _buildInput('备注', _remarkController,false,5 ),
                      // _buildInput('数量', _sonNumController, true),
                      _buildInputWrap(widget.type)
                    ],
                  )),
            ),
            Container(
              height: 120.w,
              // color: Utils.hexToColor('#FFFFFF'),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1, color: Utils.hexToColor('#F2F2F2')))),
              child: SizedBox(
                width: 620.w,
                height: 76.w,
                child: ElevatedButton(
                  onPressed: () {
                    if (widget.type == 'num') {
                      _editNum();
                    }
                    if (widget.type == 'remark') {
                      _editRemark();
                    }
                  },
                  child: Text(
                    '保存',
                    style: TextStyle(color: Colors.white),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF297CFF),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(60.w))),
                  ),
                ),
              ),
            )
          ],
        ));
  }
}
